<?php
// 创建单号
function make_order_sn()
{
    return date('YmdH') . substr(mt_rand(1000000, 999999999), 0, 4) . substr(mt_rand(1000000, 999999999), 0, 6);
}

function error_log_pay($msg)
{
    error_log_one($msg, Z_ERROR_LOG_PAY);
}

function error_log_one($msg, $file)
{
    @mkdir(dirname($file), 0777, true);
    $log_file = fopen($file, 'a+');
    fwrite($log_file, 'Date:  ' . date('Y-m-d H:i:s') . '     : ' . print_r($msg, true) . "\n\n");
}
//获取ip 地址
function get_real_ip()
{
    foreach (array('HTTP_CF_CONNECTING_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'HTTP_CLIENT_IP', 'HTTP_REMOTE_HOST', 'REMOTE_ADDR') as $key) {
        if (isset($_SERVER[$key])) {
            $ip = $_SERVER[$key];

            if (preg_match('`^(\\d{1,3}\\.){3}\\d{1,3}$`', $ip)) {
                return $ip;
            }
        }
    }

    return '0.0.0.0';
}

//根据ip地址获取地区
function GetIpLookup($ip = ''){
    if(empty($ip)){
        $ip = get_real_ip();
    }
    $res = @file_get_contents('http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=js&ip=' . $ip);
    if(empty($res)){ return false; }
    $jsonMatches = array();
    preg_match('#\{.+?\}#', $res, $jsonMatches);
    if(!isset($jsonMatches[0])){ return false; }
    $json = json_decode($jsonMatches[0], true);
    if(isset($json['ret']) && $json['ret'] == 1){
        $json['ip'] = $ip;
        unset($json['ret']);
    }else{
        return false;
    }
    return $json;
}

function static_url($resource)
{
    if (strpos($resource, '://') > 0) {
        return $resource;
    }
    $d = Z_DOMAIN;
    //$d = 'qggwsc.com';
    return '//' . Z_DOMAIN . $resource;
}

/**
 * 上传文件
 *
 * @param array $file 待上传的文件
 * @return false|string 上传成功则返回上传后的文件名（不带域名）；否则返回false
 */
function upload_file($file)
{
    //配置信息
    $config = C('STORAGE_QI_NIU');

    //创建上传器
    $upload = new \Think\Upload($config);

    //上传文件
    $info = $upload->uploadOne($file);

    if ($info) {
        return $info;
    } else {
        return false;
    }
}

//解析单图
function generate_single_image($image)
{
    if (empty($image)) {
        return array(
            "preview" => "[]",
            "previewConfig" => "[]",
        );
    } else {
        $config[] = array(
            "url" => U("Tool/deleteImage"),
            "key" => 0,
        );

        $image = array($image);
        return array(
            "preview" => json_encode($image),
            "previewConfig" => json_encode($config),
        );
    }
}

//解析多图
function generate_multi_image($imageList)
{
    if (empty($imageList)) {
        return array(
            "preview" => "[]",
            "previewConfig" => "[]",
        );
    } else {
        $config = array();
        foreach ($imageList as $key => $image) {
            $data = array(
                "url" => U("Tool/deleteImage"),
                "key" => $key,
            );
            $config[] = $data;
        }

        return array(
            "preview" => json_encode($imageList),
            "previewConfig" => json_encode($config),
        );
    }
}

/**
 * 发送邮件
 *
 * @param $receiver 接收者
 * @param $title 邮件标题
 * @param $content 邮件正文
 * @param $standby 备用信息（防止正文中的HTML标签不被识别）
 * @return bool 发送成功返回true；否则返回false
 */
function send_email($receiver, $title, $content, $standby = "")
{
    Vendor('PHPMailer.PHPMailerAutoload');
    //实例化
    $mail = new PHPMailer();
    // 启用SMTP
    $mail->IsSMTP();
    //smtp服务器的名称（这里以QQ邮箱为例）
    $mailConfig = getConfig('email');

    $mail->Host = $mailConfig['host'];
    $mail->Port = $mailConfig['port'];
    //启用smtp认证
    $mail->SMTPAuth = $mailConfig['smtpAuth'];
    //你的邮箱名
    $mail->Username = $mailConfig['name'];
    //邮箱密码
    $mail->Password = $mailConfig['password'];
    //发件人地址（也就是你的邮箱地址）
    $mail->From = $mailConfig['from'];
    //发件人姓名
    $mail->FromName = $mailConfig['fromName'];
    $mail->AddAddress($receiver, "尊敬的客户");
    //设置每行字符长度
    $mail->WordWrap = 50;
    // 是否HTML格式邮件
    $mail->IsHTML($mailConfig['isHtml']);
    //设置邮件编码
    $mail->CharSet = $mailConfig['charset'];
    //邮件主题
    $mail->Subject = $title;
    //邮件内容
    $mail->Body = $content;
    //邮件正文不支持HTML的备用显示
    $mail->AltBody = $standby;

    //发送邮件
    return $mail->Send();
}

/**
 * 格式化的当前日期
 *
 * @return false|string
 */
function now_datetime()
{
    return date("Y-m-d H:i:s");
}

/**
 * 模块名称
 * @param $module
 * @return string
 */
function moduleName($module)
{
    $modules = array(
        "deal" => "手续费",
        "rebate" => "升级配置",
        "sms" => "短信",
        "email" => "邮箱设置",
        "maker" => "做单配置"
    );
    return $modules[$module];
}

/**
 * 替代scan_dir的方法
 * @param string $pattern 检索模式 搜索模式 *.txt,*.doc; (同glog方法)
 * @param int $flags
 */
function sp_scan_dir($pattern,$flags=null){
    $files = array_map('basename',glob($pattern, $flags));
    return $files;
}

/**
 * 请求接口返回内容
 * @param  string $url [请求的URL地址]
 * @param  string $params [请求的参数]
 * @param  int $ipost [是否采用POST形式]
 * @return  string
 */
function juhecurl($url, $params = false, $ispost = 0)
{
    $httpInfo = array();
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HTTP_VERSION, CURL_HTTP_VERSION_1_1);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 5.1) AppleWebKit/537.22 (KHTML, like Gecko) Chrome/25.0.1364.172 Safari/537.22');
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    if ($ispost) {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
        curl_setopt($ch, CURLOPT_URL, $url);
    } else {
        if ($params) {
            curl_setopt($ch, CURLOPT_URL, $url . '?' . $params);
        } else {
            curl_setopt($ch, CURLOPT_URL, $url);
        }
    }
    $response = curl_exec($ch);
    if ($response === FALSE) {
        return false;
    }
    $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $httpInfo = array_merge($httpInfo, curl_getinfo($ch));
    curl_close($ch);
    return $response;
}

// 数组转为csv
function array2csv(array &$array)
{
    if (count($array) == 0) {
        return null;
    }
    ob_start();
    $df = fopen("php://output", 'w');
    foreach ($array as $row) {
        fputcsv($df, $row);
    }
    fclose($df);
    return ob_get_clean();
}

// 生成下载文件头部信息
function downloadHeaders($filename) {
    // disable caching
    $now = gmdate("D, d M Y H:i:s");
    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Cache-Control: max-age=0, no-cache, must-revalidate, proxy-revalidate");
    header("Last-Modified: {$now} GMT");

    // force download
    header("Content-Type: application/force-download");
    header("Content-Type: application/octet-stream");
    header("Content-Type: application/download");

    // disposition / encoding on response body
    header("Content-Disposition: attachment;filename={$filename}");
    header("Content-Transfer-Encoding: binary");
}

/**
 * 获取图片缩放
 * @param $img 图片路径
 */
function getZoomImg($img){
    return $img."?imageMogr2/thumbnail/!50p/blur/1x0/quality/100|imageslim";
}

/**
 * 获取地址路径
 */
function getIdPath($regionId){
    $region = M('region')->field("id_path")->where(array("id" => $regionId))->find();
    return $region['id_path'];
}

// 发货
function send($id, $logisticsCom, $logistics, $tracingSns)
{
    // 获取订单数据
    $order = M('order')->where(array("id" => $id))->find();

    // 没有订单
    if(empty($order)){
        return "订单为空";
    }

    // 订单状态不对
    if($order['status'] != 2){
        return "订单状态错误！";
    }

    M()->startTrans();

    if(!empty($tracingSns) && count($tracingSns) > 0){

        // 获取流转信息
        $flowInfo = getFlowInfo($id , $order);

        // 更新流转信息
        $msg = updateTracing($tracingSns,$flowInfo);
        if(!empty($msg)){
            M()->rollback();
            return $msg;
        }
    }

    // 更新订单
    $order['status'] = 3;
    $order['logisticsCom'] = $logisticsCom;
    $order['logistics'] = $logistics;
    $order['updateTime'] = date("Y-m-d H:i:s");
    $r[] = M('order')->where(array("id" => $id))->save($order);

    // 如果有错误
    if(in_array(false , $r)){
        M()->rollback();
       return "发货失败";
    }else{
        M()->commit();
        return "";
    }
}

// 获取流转信息
function getFlowInfo($id, $newFlow)
{
    $flowInfo = "";
    $flowAgen = "";
    $flows = array();
    $list = M('flow')
        ->alias("t")
        ->join(" LEFT JOIN agen ba ON ba.id = t.beforeId")
        ->join(" LEFT JOIN agen aa ON aa.id = t.afterId")
        ->field("t.beforeId,t.afterId,ba.level as beforelevel,ba.phone as beforeAccount,aa.level as afterlevel,aa.phone as afterAccount")
        ->order(" t.id desc ")
        ->where(array("t.sourceType" => 1, "t.sourceId" => $id))
        ->select();

    // 如果没有流转记录，讲本次发货添加到流转记录里面
    if(count($list) <= 0){
        $list[] = $newFlow;
    }

    // 根据流转记录获取流转信息
    for ($i = 0; $i < count($list); $i++) {
        $flow = $list[$i];
        if ($i == 0) {
            // 如果最后是厂家
            if ($flow['afterid'] == 1) {
                $startFlowInfo = "厂家";
                $startFlowAgen = "1";
            } else {
                $startFlowInfo = getLevelList($flow['afterlevel']) . "(" . $flow['afteraccount'] . ")";
                $startFlowAgen = $flow['afterid'];
            }
        }

        $flowInfo .= " > " . getLevelList($flow['beforelevel']) . "(" . $flow['beforeaccount'] . ")";
        $flowAgen .= "," . $flow['beforeid'];

        // 溯源流转正好跟订单流转相反
        $flows[] = array(
            "sourceType" => "3",
            "beforeId" => $flow['afterid'],
            "afterId" => $flow['beforeid'],
            "createTime" => now_datetime(),
            "info" => "溯源流转信息记录"
        );
    }

    return array(
        "startFlowInfo" => $startFlowInfo,
        "startFlowAgen" => $startFlowAgen,
        "flowInfo" => $flowInfo,
        "flowAgen" => $flowAgen,
        "flows" => $flows,
    );
}

// 更新溯源码，插入流转记录
function updateTracing($tracingSns , $flowInfo){
    // 如果没有溯源码
    if(count($tracingSns) <= 0){
        return "";
    }

    $flowAll = array();
    for($i = 0;$i < count($tracingSns);$i ++){
        $tracingSn = $tracingSns[$i];
        $tracing = M("Tracing")->where(array("sn" => $tracingSn))->find();

        // 如果
        if(empty($tracing) || $tracing['status'] == 3){
            return $tracingSn."不存在或者已经失效!";
        }

        // 如果没有流转记录
        if(empty($tracing['tracingflowinfo'])){
            // 将首次流转信息拼接
            $flow = $flowInfo['startFlowInfo'].$flowInfo['flowInfo'];
            $flowAgen = $flowInfo['startFlowAgen'].$flowInfo['flowAgen'];
        }else {
            $flow = $tracing['tracingflowinfo'].$flowInfo['flowInfo'];
            $flowAgen = $tracing['tracingflow'].$flowInfo['flowAgen'];
        }

        // 更新
        $tracingUp = array(
            "status" => 2,
            "tracingflow" => $flowAgen,
            "tracingflowInfo" => $flow,
            "updateTime" => now_datetime()
        );
        $r[] = M("tracing")->where(array("id" => $tracing['id']))->save($tracingUp);

        $flows = $flowInfo['flows'];

        for($j = 0;$j < count($flows) ;$j ++){
            $flowData = $flows[$j];
            $flowData['sourceId'] = $tracing['id'];
            $flowAll[] = $flowData;
        }
    }

    // 记录批量更新
    $r[] = M("flow")->addAll($flowAll);

    // 如果有错误
    if(in_array(false , $r)){
        return "流转记录失败";
    }else{
        return "";
    }
}

/**
 * 厂家审核代理
 * @param $agenReview
 * @return string
 */
function agenReview($agenReview){
    $agen = M('Agen')->where(array('id' => $agenReview['agenid']))->find();
    $reviewAgen = M('agen')->where(array('id' => $agenReview['reviewid']))->find();

    // 如果有一个为空，异常
    if(empty($agen) || empty($agenReview) || empty($reviewAgen)){
        return '数据异常！';
    }

    // 升级申请
    if($agenReview['type'] == 2){
        // 更新代理等级，上级
        $data['level'] = $agenReview['level'];
        $data['upagenid'] = $reviewAgen['id'];
        $data['upagenAccount'] = $reviewAgen['account'];
        // 根据上级代理关系生成新的关系
        $data['relation'] = $agenReview['relation'] . ',' . $agenReview['agenid'];

        $r[] = M('agen')->where(array('id' => $agenReview['agenid']))->setField($data);
    }else{
        // 更新代理上级，状态
        $data['status'] = "2";
        $data['isDisable'] = "2";
        $data['upagenid'] = $reviewAgen['id'];
        $data['upagenAccount'] = $reviewAgen['account'];

        // 注册代理为已审核
        $r[] = M('agen')->where(array('id' => $agenReview['agenid']))->setField($data) ;
    }

    // 审核状态
    $r[] = M('AgenReview')->where(array('id' => $agenReview['id']))->setField("status" ,3);

    // 如果成功
    if (!in_array(false, $r)) {
        return "";
    } else {
        return "代理审核失败！";
    }
}

/**
 * 审核报单
 *
 * @param $id 报单订单
 * @param bool $isDeduct 是否扣除库存
 * @param bool $isAdd 是否增加下级代理库存
 * @param string $info 库存日志
 * @return string 如果有错误返回错误信息，没有成功
 */
function reportReview($id ,$isDeduct = true , $isAdd = true , $info = '审核报单'){
    // 审核报单
    $agenOrder = M('OnlineOrder')->where(array('id' => $id , 'status' => 1))->find();
    $agen = M('Agen')->where(array('id' => $agenOrder['sourceid']))->find();
    $orderDetails = M('OrderDetails')->where(array('orderId' => $agenOrder['id'], 'orderType' => $agenOrder['ordertype']))->select();
    $reviewAgen = M('agen')->where(array('id' => $agenOrder['toagenid']))->find();

    // 如果有一个为空，异常
    if(empty($agenOrder) || empty($agen)|| empty($orderDetails) || empty($reviewAgen) ){
        return '数据异常！';
    }

    // 非厂家时候，判断审核人员等级
    if($agenOrder['toagenid'] != 1 && $agen['level'] <= $reviewAgen['level']){
        return '审核代理等级不足！';
    }

    // 需要扣除库存，并且不是厂家时候，扣除库存
    if($agenOrder['toagenid'] != 1 && $isDeduct){
        // 获取审核订单
        foreach ($orderDetails as $orderDetail) {

            // 库存是否足够
            $productStock = M('agenStock')->where(array('agenId' => $reviewAgen['id'], 'productId' => $orderDetail['productid']))->find();

            // 库存不足
            if(empty($productStock) || $productStock['num'] < $orderDetail['num']){
                return '审核代理库存不足！';
            }

            // 扣除库存
            $r[] = M('agenStock')->where(array('agenId' => $reviewAgen['id'], 'productId' => $orderDetail['productid']))->setDec('num', $orderDetail['num']);
            $r[] = stockLog($reviewAgen['id'], $id, $orderDetail['productid'], -$orderDetail['num'], $productStock['num'], $info);
        }
    }

    // 增加申请代理库存
    if($isAdd){
        foreach ($orderDetails as $orderDetail) {

            // 库存是否足够
            $productStock = M('agenStock')->where(array('agenId' => $agen['id'], 'productId' => $orderDetail['productid']))->find();

            // 库存不足
            if(empty($productStock)){
                $r[] = M('agenstock')->add(array(
                    'agenId' => $agen['id'],
                    'productId' => $orderDetail['productid'],
                    'num' => $orderDetail['num']
                ));
            }else{

                // 增加库存
                $r[] = M('agenStock')->where(array('agenId' => $agen['id'], 'productId' => $orderDetail['productid']))->setInc('num', $orderDetail['num']);
            }

            // log
            $r[] = stockLog($agen['id'], $id, $orderDetail['productid'], $orderDetail['num'], $productStock['num'], $info);
        }

        // 更新状态
        $r[] =  M('OnlineOrder')->where(array('id' => $id))->save(array("status" => '3'));

        // 添加发展人返佣，厂家审核增加返佣（代理审核不增加申请代理库存，不增加返佣）
        if (!empty($agen['recommendid']) && $agen['recommendid'] != $agenOrder['toagenid']) {

            // 发展人
            $recommend = M('agen')->where(array('id' => $agen['recommendid']))->find();
            // 上级代理人
            $upagen = M('agen')->where(array('id' => $agenOrder['toagenid']))->find();

            // 上级代理跟报单人的订单额之差
            $totalchange = $agenOrder['total' . $agen['level']] - $agenOrder['total' . $upagen['level']];
            if(empty($totalchange)){
                $totalchange = 0;
            }

            // 获取系统返佣比例系统可配置 * 差值
            $difference = $totalchange * getConfig('site', 'difference');

            // 如果是一级代理，固定返佣
            if ($agen['level'] == 1) {
                $difference = $agenOrder['rebatetotal'];

                // 如果发展人定义返佣比例
            }else if (!empty($recommend['rebate']) && $recommend['rebate'] > 0) {
                $difference = $totalchange * $recommend['rebate'];
            }

            // 如果有订单差值，并且发展人不是厂家
            if ($difference > 0 && $recommend['id'] != 1) {

                // 返佣记录
                $differencedb = array(
                    'arrearsId' => $upagen['id'],
                    'accountId' => $recommend['id'],
                    'sourceId' => $agenOrder['id'],
                    'type' => 2,
                    'money' => $difference,
                    'status' => '1',
                    'createTime' => now_datetime(),
                    'fromagenid' => $agen['id']
                );
                M('difference')->add($differencedb);
            }
        }
    }

    // 如果成功
    if (!in_array(false, $r)) {
        return "";
    } else {
        return "报单审核失败！";
    }
}

// 获取代理URL
function getAgenUrl($no){
    return "http://".$_SERVER['HTTP_HOST']."/Home/Index/index?id=".$no;
}

// 余额动态释放
function balanceRelease($user,$banlance,$reflectId){
    $system=getConfig("rakeback");
    $onebalance=$banlance*$system['oneRate'];
    $twobalance=$banlance*$system['twoRate'];
    $otherbalance=$banlance*$system['otherRate'];
    $returndata=1;
    if(!empty($user) && !empty($user['parentid'])){
        for($i=1;$i<=$system['members'];$i++){
            //上级推荐人
            $user=M("member")->where(array("id"=>$user['parentid']))->find();
            if(empty($user)){
                break;
            }
            //推荐人推荐的个数
            //往上找满足9代，判断推荐人数
            if($i>$system['subMember']){
                $count=M("member")->where(array("parentId"=>$user['id']))->count();
                if($count<5){//推荐人数小于5人不拿
                    continue;
                }else{
                    if($otherbalance>=0.01){//小于0.01,数据库没有改变则返回错误
                        //$add_log = balancelog($reflectId, $user['id'], +$otherbalance, $type=14, $before=$user['balance'], $after=$user['balance']+$otherbalance);
                        $save_mem=M("member")->where(array("id"=>$user['id']))->setInc("other_balance",$otherbalance);
                        //积分变更
                        /*if($user['integral']>0 && $user['integral']<$otherbalance){//有积分但是不够扣的，改为0；
                            $reduceItg=$user['integral'];//减少积分
                            $remainitg=0;//剩余积分
                            $integrallog=integrallog($reflectId, $user['id'],-$reduceItg,6,$user['integral'],$remainitg);//返佣积分log
                            $memItg=M("member")->where(array("id"=>$user['id']))->save(array("integral"=>$remainitg));//更改用户积分
                        }else if($user['integral']>0 && $user['integral']>$otherbalance){
                            $reduceItg=$otherbalance;//减少积分
                            $remainitg=$user['integral']-$otherbalance;//剩余积分
                            $integrallog=integrallog($reflectId, $user['id'],-$reduceItg,6,$user['integral'],$remainitg);//返佣积分log
                            $memItg=M("member")->where(array("id"=>$user['id']))->save(array("integral"=>$remainitg));//更改用户积分
                        }else{//积分为0，不添加log
                            $integrallog=1;
                            $memItg=1;
                        }*/
                        //$data=$add_log && $save_mem && $integrallog && $memItg;
                        //$data=$save_mem && $integrallog && $memItg;
                        $data=$save_mem;
                        $returndata=$returndata && $data;
                    }
                }
            }else if($i<=$system['subMember']){//不满足9代，都要拿，无论推荐几个人
                $data=updateMemberRebate($i,$user,$onebalance,$twobalance,$otherbalance);
                $returndata=$returndata && $data;
            }
        }
    }
    $returndata=$returndata;
    return $returndata;
}

/**
 * 提取出来的返佣的方法
 * @param $i
 * @param $user
 * @param $onebalance
 * @param $twobalance
 * @param $otherbalance
 * @return bool|int
 */
function updateMemberRebate($i,$user,$onebalance,$twobalance,$otherbalance){
    if($i==1 && $onebalance>=0.01){//第一代返佣
        //分开插入member,目的就是在积分为负值的时候不要更改原有数据
        //$add_log = balancelog($reflectId, $user['id'], +$onebalance, $type=14, $before=$user['balance'], $after=$user['balance']+$onebalance);
        $save_mem=M("member")->where(array("id"=>$user['id']))->setInc("other_balance",$onebalance);
        /* if($user['integral']>0 && $user['integral']<$onebalance){//有积分但是不够扣的，改为0；
             $reduceItg=$user['integral'];//减少积分
             $remainitg=0;//剩余积分
             $integrallog=integrallog($reflectId, $user['id'],-$reduceItg,6,$user['integral'],$remainitg);//返佣积分log
             $memItg=M("member")->where(array("id"=>$user['id']))->save(array("integral"=>$remainitg));//更改用户积分
         }else if($user['integral']>0 && $user['integral']>$onebalance){
             $reduceItg=$onebalance;//减少积分
             $remainitg=$user['integral']-$onebalance;//剩余积分
             $integrallog=integrallog($reflectId, $user['id'],-$reduceItg,6,$user['integral'],$remainitg);//返佣积分log
             $memItg=M("member")->where(array("id"=>$user['id']))->save(array("integral"=>$remainitg));//更改用户积分
         }else{//积分为0，不添加log
             $integrallog=1;
             $memItg=1;
         }*/
    }else if($i==2 && $twobalance>=0.01){//第二代返佣
        //$add_log = balancelog($reflectId, $user['id'], +$twobalance, $type=14, $before=$user['balance'], $after=$user['balance']+$twobalance);
        $save_mem=M("member")->where(array("id"=>$user['id']))->setInc("other_balance",$twobalance);
        //变更积分
        /* if($user['integral']>0 && $user['integral']<$twobalance){//有积分但是不够扣的，改为0；
             $reduceItg=$user['integral'];//减少积分
             $remainitg=0;//剩余积分
             $integrallog=integrallog($reflectId, $user['id'],-$reduceItg,6,$user['integral'],$remainitg);//返佣积分log
             $memItg=M("member")->where(array("id"=>$user['id']))->save(array("integral"=>$remainitg));//更改用户积分
         }else if($user['integral']>0 && $user['integral']>$twobalance){
             $reduceItg=$twobalance;//减少积分
             $remainitg=$user['integral']-$twobalance;//剩余积分
             $integrallog=integrallog($reflectId, $user['id'],-$reduceItg,6,$user['integral'],$remainitg);//返佣积分log
             $memItg=M("member")->where(array("id"=>$user['id']))->save(array("integral"=>$remainitg));//更改用户积分
         }else{//积分为0，不添加log
             $integrallog=1;
             $memItg=1;
         }*/
    }else if($otherbalance>=0.01){
        //$add_log = balancelog($reflectId, $user['id'], +$otherbalance, $type=14, $before=$user['balance'], $after=$user['balance']+$otherbalance);
        $save_mem=M("member")->where(array("id"=>$user['id']))->setInc("other_balance",$otherbalance);
        //积分变更
        /*if($user['integral']>0 && $user['integral']<$otherbalance){//有积分但是不够扣的，改为0；
            $reduceItg=$user['integral'];//减少积分
            $remainitg=0;//剩余积分
            $integrallog=integrallog($reflectId, $user['id'],-$reduceItg,6,$user['integral'],$remainitg);//返佣积分log
            $memItg=M("member")->where(array("id"=>$user['id']))->save(array("integral"=>$remainitg));//更改用户积分
        }else if($user['integral']>0 && $user['integral']>$otherbalance){
            $reduceItg=$otherbalance;//减少积分
            $remainitg=$user['integral']-$otherbalance;//剩余积分
            $integrallog=integrallog($reflectId, $user['id'],-$reduceItg,6,$user['integral'],$remainitg);//返佣积分log
            $memItg=M("member")->where(array("id"=>$user['id']))->save(array("integral"=>$remainitg));//更改用户积分
        }else{//积分为0，不添加log
            $integrallog=1;
            $memItg=1;
        }*/
    }else{
        //$add_log=1;
        $save_mem=1;
        //$integrallog=1;
        //$memItg=1;
    }
    //$data=$add_log && $save_mem && $integrallog && $memItg;
    //$data=$save_mem && $integrallog && $memItg;
    return $save_mem;
}

/**
 * 积分兑换返佣
 * @param $user
 * @param $integral 转换以后的积分
 * @param $reflectId 关联id
 * @return bool|int
 */
function exchangeRelease($user,$balance,$reflectId){
    $system=getConfig("rakeback");
    //$bonus=getConfig("bonus");
    $onebalance=$balance*$system['oneExchangeRate'];
    $twobalance=$balance*$system['twoExchangeRate'];
    $otherbalance=$balance*$system['otherExchangeRate'];
    //$returnbalance=$balance*$system['signRate']*$system['exchangeRate'];//转换后的积分乘以积分的每日反余额比例千分之二再乘以积分释放比例
    $returndata=1;
    if(!empty($user) && !empty($user['parentid'])) {
        for ($i = 1; $i <= $system['members']; $i++) {
            //上级推荐人
            $user = M("member")->where(array("id" => $user['parentid']))->find();
            if (empty($user)) {
                break;
            }
            $data=updateMemberRebate($i,$user,$onebalance,$twobalance,$otherbalance);
            $returndata=$returndata && $data;
        }
    }
    /*if($returnbalance>=0.01){
        if(!empty($user) && !empty($user['parentid'])){
            for($i=1;$i<=$system['exchangeMember'];$i++){
                $user=M("member")->where(array("id"=>$user['parentid']))->find();
                if(empty($user) || empty($user['parentid'])){
                    break;
                }
                $save_mem=M("member")->where(array("id"=>$user['id']))->save(array("other_balance"=>($user['other_balance']+$returnbalance)));
                $data=$save_mem;
                $returndata=$returndata && $data;
            }
        }
    }*/
    return $returndata;
}

